﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Prism.WebBuilder.Processors.Base;
using Prism.WebBuilder.Lib.Cui;

namespace Prism.WebBuilder.Processors
{
	public class Call : ProcessorBase
	{
		private string _program;
		private object[] _args;

		public Call Init(string name, params object[] args)
		{
			_program = name;
			_args = args;
			return this;
		}

		public override void Process()
		{
			IEnumerable<string> ar = _args
				.Select(a => resolvePath(a.ToString()))
				.Select(x => wrapArg(x));

			var startPath = resolvePath(_program);
			var startArgs = string.Join(" ", ar);
			var finalCmdParam = "/c \"" + wrapArg(startPath) + " " + startArgs + "\"";
			Cui.Info("start cmd {0}", finalCmdParam);
			
			var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
				{
					FileName = "cmd",
					Arguments = finalCmdParam,
					UseShellExecute = false,
					CreateNoWindow = true
				});
			process.WaitForExit();
			base.Process();
		}

		string resolvePath(string path)
		{
			return path.Contains("?")
					? ResolvePath(path.Replace("?", ""))
					: path;
		}

		string wrapArg(string x)
		{
			//return x;
			return x.Contains(" ")
					? ("\"" + x + "\"")
					: x;
		}
	}
}
